import { Space, Drawer, Col, Row, Select, Modal, Timeline, Message } from 'antd';
import React, { Fragment, useEffect } from 'react';
import { useTablePipeline, features } from 'ali-react-table';
import { HttpCode } from '#/utils/contacts.js';
import { TjTable } from '@/pages/ETrade/components';
import TRNotification from '#/utils/notification.js';
import { useTRState } from '#/utils/trHooks.jsx';
import previewIcon from '@/assets/img/preview_icon.png';
import styles from './index.less';
import { configArr, baseTableStyle, overviewColumns, done_config } from '../Container/helper';
import SelectPersonnel from '../SelectPersonnel';
import { aveGreenCertificateInfo, stationDetailData, queryOperationLog } from '../../services';
import { getTableData } from '../../helper';
import plan_icon from '@/assets/img/plan_icon.png';
const Component = ({ formValues, dataType, code, value, onChange, ...arg }) => {
  let _value = formValues[code] == undefined ? value : formValues[code];
  switch (dataType) {
    case 'select':
      return <SelectPersonnel value={_value} code={code} onChange={onChange} {...arg} />;
    case 'done_select':
      _value = typeof _value === 'number' ? (_value ? '已办完' : '未办完') : _value;
      return (
        <Select
          style={{ width: '100%', height: 32 }}
          value={_value}
          options={done_config}
          showArrow
          onChange={(v) => {
            onChange({ [code]: v });
          }}
        />
      );
    default:
      return (
        <div className={styles.content_item_info}>
          {typeof value === 'number' ? (value ? '已办完' : '未办完') : value || '无'}
        </div>
      );
  }
};

export const ModalComponent = ({ type, row, personList, getDataSource, onPress }) => {
  const [state, setState] = useTRState({
    formValues: {},
    canEdit: type === 'edit',
    editing: type === 'edit',
    visible: true,
    isLogVisible: false,
    tableData: [],
    info: row,
    logList: [],
  });
  const [openKeys, onChangeOpenKeys] = React.useState([1]);
  useEffect(async () => {
    const res = await stationDetailData({
      stationId: row.stationId,
      startMonth: row.startMonth,
      endMonth: row.endMonth,
    });
    if (res?.statusCode === HttpCode.SUCCESS && res.data?.size > 0) {
      const { tableData, exportTable } = getTableData(res.data);
      setState({
        tableData,
      });
    }
    setState({
      info: row,
    });
  }, [row]);
  useEffect(async () => {
    if (!state.editing) {
      const res = await queryOperationLog(row.stationId);
      if (res?.statusCode === HttpCode.SUCCESS) {
        let list = [];
        res.data.map((x) => {
          personList.map((y) => {
            if (x.operatorId == y.userId) {
              list.push({
                ...x,
                name: y.name,
                showMore: false,
              });
            }
          });
        });
        setState({
          logList: list,
        });
      }
    }
  }, [state.editing, row]);

  const _onClose = () => {
    setState({ visible: false });
    onPress({ index: 0 });
  };
  const toggle = () => {
    setState({ editing: !editing });
  };

  const onSave = async () => {
    if (JSON.stringify(state.formValues) == '{}') {
      return Message.error('暂无更改！');
    }
    const res = await aveGreenCertificateInfo({ ...state.formValues, stationId: row.stationId });
    if (res?.statusCode === HttpCode.SUCCESS) {
      Message.info('保存成功');
      setState({ info: { ...state.info, ...state.formValues } });
      toggle();
      getDataSource?.();
    } else {
      Message.error('保存失败，请重试。');
    }
    // _onOk()
  };
  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: state.tableData, columns: overviewColumns })
    .primaryKey('id')
    .use(
      features.treeMode({
        openKeys,
        onChangeOpenKeys,
        indentSize: 20,
        iconIndent: 5,
      }),
    );
  const { visible, formValues, canEdit, editing, isLogVisible, logList } = state;
  return (
    <Drawer
      visible={visible}
      title={
        <div>
          <div className={styles.drawer_title}>
            <img
              src={plan_icon}
              width="24px"
              height="24px"
              style={{ marginRight: 4, marginTop: '-2px' }}
            />
            场站详情
          </div>
          <div className={styles.breadcrumb}>
            <div className={styles.breadcrumb_left}>
              <span>场站概览</span>
              <span>/</span>
              <span className={styles.breadcrumb_check}>{canEdit ? '编辑' : '查看'}</span>
            </div>
            <Space className={styles.breadcrumb_right}>
              {canEdit ? (
                !editing ? (
                  <a onClick={toggle}>编辑</a>
                ) : (
                  <>
                    <a onClick={onSave}>保存</a>
                    <a onClick={toggle}>取消</a>
                  </>
                )
              ) : (
                ''
              )}
              <span>
                <a onClick={() => setState({ isLogVisible: true })}>变更记录</a>
              </span>
            </Space>
          </div>
        </div>
      }
      width={'90%'}
      placement={'right'}
      destroyOnClose={true}
      getContainer={false}
      onClose={_onClose}
    >
      <div className={styles.body}>
        {configArr(editing).map((t, i) => (
          <Fragment key={i}>
            <div className={styles.title}>{t.title}</div>
            <div className={styles.content}>
              <Row gutter={80}>
                {t.columns.map((props, index) => (
                  <Col span={props.span} key={index}>
                    <div className={styles.content_item} key={index}>
                      <div className={styles.content_item_label}>{props.title}</div>
                      <Component
                        {...props}
                        value={state.info[props.code]}
                        formValues={formValues}
                        personList={personList}
                        onChange={(v) => {
                          setState({
                            formValues: {
                              ...formValues,
                              ...v,
                            },
                          });
                        }}
                      />
                    </div>
                  </Col>
                ))}
              </Row>
            </div>
          </Fragment>
        ))}
        <TjTable
          style={{ ...baseTableStyle, marginTop: 8 }}
          useOuterBorder={true}
          stickyScrollHeight={10}
          useVirtual={{ horizontal: true, vertical: true, header: false }}
          defaultColumnWidth={100}
          {...pipeline.getProps()}
        />
      </div>
      <Modal
        centered
        width={560}
        closable={true}
        visible={isLogVisible}
        onCancel={() => {
          setState({ isLogVisible: false });
        }}
        zIndex={2500}
        title={
          <div className={styles.modalEdit}>
            <img src={previewIcon} />
            <span>操作日志</span>
          </div>
        }
        wrapClassName={styles.logModal}
        footer={null}
      >
        <Timeline>
          {logList.map((item, index) => {
            return (
              <Timeline.Item key={index} color={'gray'}>
                <div className={styles.text_time_div}>
                  <div className={styles.text_time_line}>{item.createTime}</div>
                  <div className={styles.text_operation_name}>
                    操作人：<span>{item.name}</span>
                  </div>
                </div>
                {item.description.length > 1 && (
                  <a
                    className={styles.text_more}
                    onClick={() => {
                      let list = [...logList];
                      list[index].showMore = !list[index].showMore;
                      setState({ logList: list });
                    }}
                  >
                    {item.showMore ? '收起' : '展开'}
                  </a>
                )}
                <div className={styles.content_list}>
                  {!item.showMore ? (
                    <div>{item.description?.[0]}</div>
                  ) : (
                    item.description.map((item1) => {
                      return <div>{item1}</div>;
                    })
                  )}
                </div>
              </Timeline.Item>
            );
          })}
        </Timeline>
      </Modal>
    </Drawer>
  );
};

class DetailModal {
  __key__ = '';

  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ModalComponent
            {...props}
            onPress={(result) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new DetailModal();
